package com.ghsc.ghxc.jsb.ui.message.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.flyco.roundview.RoundTextView
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityChatListBinding
import com.ghsc.ghxc.jsb.ui.message.bean.ChatDataResultBean
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.ghsc.ghxc.jsb.view.NotDataView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.activity
 * 类名：ChatListAddActivity
 * 创建时间：2024/5/9 14:27
 * 创建人 @author： xiaolin
 * 描述 ：Todo...好友列表  群  邀请xxx。xx
 */
class ChatListAddActivity : BaseVMActivity<ChatViewModel, ActivityChatListBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_chat_list
    }

    override fun attachVMClass(): Class<ChatViewModel>? {
        return ChatViewModel::class.java
    }

    private val mAdapter: SearchChatAdapter by lazy { SearchChatAdapter() }
    var mList = arrayListOf<ChatDataResultBean>()
    private var notDataView: View? = null
    var keyword: String = ""

    var itemPosition = -1

    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }

    var bundle: Bundle? = null
    var gid: String = ""

    @SuppressLint("SetTextI18n")
    override fun initView() {
        bundle = intent.extras
        gid = bundle!!.getString("gid", "")
        binding.run {
            tvBtnCheck.visibility  = View.VISIBLE
            tvBtnCheck.text = "确定(0)"
            topLeftView.setOnClickListener {
                hideKeyboard(etSearch)
                finish()
            }
            topTitle.text = "我的好友"
            tvBtnNext.setOnClickListener {
                if (TextUtils.isEmpty(binding.etSearch.text)) {
                    showToast("请输入邀请码/手机号")
                } else {
                    pageNo = 1
                    getListData()
                }
            }
            etSearch.isFocusable = true
            etSearch.isFocusableInTouchMode = true
            etSearch.requestFocus()
            etSearch.setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = binding.etSearch.text.toString().trim()
                    if (!TextUtils.isEmpty(keyword)) {
                        binding.etSearch.clearFocus()
                        hideKeyboard(binding.etSearch)
                        pageNo = 1
                        getListData()
                    }
                }
                false
            }
        }
        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        notDataView = NotDataView.notDataView(this, binding.rvList, binding.refreshLayout, "暂无数据")
        mAdapter.setOnItemLongClickListener { adapter, view, position ->
            //长按事件
            XPopup.Builder(this@ChatListAddActivity)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .asCustom(
                    ConfirmCancelPopViiew(
                        this@ChatListAddActivity, "提示", "确定要删除该好友吗？",
                        btnConfirm = {
                            itemPosition = position
                            val map: HashMap<String, Any> = HashMap()
                            map["fuid"] = mAdapter.getItem(position).uid
                            GsonUtil.mapToJsonStrObjEncryption(map)
                                ?.let { it1 -> mViewModel.onDeleteFriendMethod(it1) }
                        },
                        btnCancel = {
                        },
                    )
                )
                .show()
            false
        }
        mAdapter.addChildClickViewIds(R.id.tvBtnNext, R.id.imgCheck)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            //item里面某个按钮事件
            when (view.id) {
//                R.id.tvBtnNext -> {
//                    if (mAdapter.getItem(position).status == -2) {
//                        itemPosition = position
//                        val map: HashMap<String, Any> = HashMap()
//                        map["fuid"] = mAdapter.getItem(position).uid
//                        map["ptype"] = 1
//                        //1是同意
//                        GsonUtil.mapToJsonStrObjEncryption(map)
//                            ?.let { it1 -> mViewModel.onActFriendMethod(it1) }
//                    }
//                }
                R.id.imgCheck -> {
                    if (mAdapter.data[position].ifingroup==1)return@setOnItemChildClickListener
                    mAdapter.data[position].isCheck = !mAdapter.data[position].isCheck
                    mAdapter.notifyItemChanged(position)
                    binding.tvBtnCheck.text = "确定(" + setCheckNum().size.toString() + ")"
                }
            }
        }
        initRefreshLayout()
        pageNo = 1
        getListData()
    }

    /** 选择好的id **/
    fun setCheckNum(): MutableList<String> {
        var mList = arrayListOf<String>()
        for (i in mAdapter.data.indices) {
            if (mAdapter.data[i].ifingroup==0){
                if (mAdapter.data[i].isCheck)
                    mList.add(mAdapter.data[i].uid)
            }
        }
        return mList

    }

    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }

    override fun initData() {
        super.initData()
        binding.tvBtnNext.setOnClickListener {
            keyword = binding.etSearch.text.toString().trim()
            if (!TextUtils.isEmpty(keyword)) {
                binding.etSearch.clearFocus()
                hideKeyboard(binding.etSearch)
                pageNo = 1
                getListData()
            }
        }
        binding.tvBtnCheck.setSingleClickListener {
            var counts = setCheckNum()
            if (counts.size > 0) {
                var str = StringUtil.convertListToString(counts)
                val map: HashMap<String, Any> = HashMap()
                map["gid"] = gid
                map["userids"] = str!!
                map["ptype"] = 2
                GsonUtil.mapToJsonStrObjEncryption(map)
                    ?.let { it1 -> mViewModel.onGroupJoinMethod(it1) }

            } else showToast("请选择您的好友进群")
        }
    }


    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["keyword"] = keyword
        map["gid"] = gid
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onFriendListMethod(it1) }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ChatListAddActivity) {
                binding.refreshLayout.finishRefresh()
                showToast(it)
            }
            againLoginMsg.observe(this@ChatListAddActivity) {
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onGroupJoinData.observe(this@ChatListAddActivity){
                showToast("邀请成功")
                finish()
            }
            onDeleteFriendData.observe(this@ChatListAddActivity){
                //删除好友
                if (itemPosition>-1){
                    mAdapter.removeAt(itemPosition)
                }
                mAdapter.notifyItemChanged(itemPosition)
            }
//            onActFriendData.observe(this@ChatListAddActivity){
//                //同意加好友
//                showToast("操作成功")
//                if (itemPosition>-1){
//                    mAdapter.getItem(itemPosition).status=1
//                }
//                mAdapter.notifyItemChanged(itemPosition)
//            }
            onFriendListData.observe(this@ChatListAddActivity, Observer {
                //我的好友列表
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()) {
                        mAdapter.replaceData(it.data.list)
                        mAdapter.setEmptyView(notDataView!!)
                    } else {
                        mAdapter.replaceData(it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
            })


        }
    }


    inner  class SearchChatAdapter   : BaseQuickAdapter<ChatDataResultBean, BaseViewHolder>(
        R.layout.friends_item) {

        override fun convert(helper: BaseViewHolder, item: ChatDataResultBean) {
            GlideUtil.ImageHeadLoad(this.context,item.headimg,helper.getView(R.id.userImgUrl))
            helper.setText(R.id.tvName,item.nickname)
            var textStatus=helper.getView<RoundTextView>(R.id.tvBtnNext)
            if (item.uid==CustKey.CHAT_SYSY_ID){
                textStatus.visibility= View.GONE
                helper.setGone(R.id.imgCheck,true)
            }else{
                //1 双方都通过   -1显示等待通过状态 -2 显示通过 按钮
                if (item.status==1) {
                    textStatus.visibility= View.GONE
                    helper.setGone(R.id.imgCheck,false)
                    //如果要是在群里
                    if (item.ifingroup==1){
                        helper.getView<ImageView>(R.id.imgCheck).setImageResource(R.drawable.check_true_red)
                    }else{
                        helper.getView<ImageView>(R.id.imgCheck).setImageResource(
                            if(item.isCheck)  R.mipmap.icon_cb_default_checked
                            else R.mipmap.icon_cb_default_not_checked)
                    }
                }
                else if (item.status==-1){
                    textStatus.visibility= View.VISIBLE
                    textStatus.text="等待通过"
                    textStatus.delegate.backgroundColor= this.context.getCompatColor(R.color.btn_lvse)
                    helper.setGone(R.id.imgCheck,true)
                }else if (item.status==-2){
                    textStatus.visibility= View.VISIBLE
                    textStatus.text="通过"
                    textStatus.delegate.backgroundColor=this.context.getCompatColor(R.color.btn_default_color)
                }else {
                    textStatus.visibility= View.GONE
                    helper.setGone(R.id.imgCheck,true)
                }
            }






        }
    }

}
